<template>
  <view class="login-container">
    <!-- 启动页 -->
    <view class="splash-screen">
      <view class="background-overlay"></view>
      <view class="content">
        <view class="logo-section">
          <image
            src="https://jyoungy.oss-cn-beijing.aliyuncs.com/jyy-mini-sale/login/logo.png"
            class="logo-icon"
            mode="widthFix"
          ></image>
        </view>
        <view class="button-section">
          <button
            class="primary-btn"
            :open-type="agreedToTerms ? 'getPhoneNumber' : ''"
            @getphonenumber="handleOneKeyLogin"
            @click="handleClick"
          >
            一键登录
          </button>
          <button class="secondary-btn" @click="goToPhoneLogin">
            其他手机号登录
          </button>
        </view>

        <view class="agreement-section">
          <label class="agreement-checkbox">
            <checkbox-group @change="onAgreementChange" class="agreement-checkbox-group">
              <checkbox
                :value="agreedToTerms"
                color="#000"
                style="transform: scale(0.4)"
                class="agreement-checkbox-item"
              />
            </checkbox-group>
            <text class="agreement-text"
              >我已阅读并同意《用户协议》《个人信息保护政策》《账号规则》</text
            >
          </label>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { authApi } from '@/request/api.js'
import authManager from '@/utils/auth.js'
import cartManager from '@/utils/cart.js'

export default {
  data() {
    return {
      // 表单数据
      agreedToTerms: false,
      loginCode: '',
      userInfo: {}
    };
  },

  methods: {
    async handleClick(e) {
      if (!this.agreedToTerms) {
        uni.showToast({
          title: "请先同意用户协议",
          icon: "none",
        });
        e.stopPropagation();
        return;
      }
      uni.getUserProfile({
        desc: '用于完善用户资料', // 声明用途
        success: (res) => {
          console.log('用户信息获取成功', res);
          this.userInfo = res.userInfo; // 保存用户信息
        },
        fail: (err) => {
          console.error('用户信息获取失败', err);
        }
      });
      this.loginCode = await this.getWechatLoginCode()
    },
    
    // 协议勾选变化
    onAgreementChange(e) {
      this.agreedToTerms = e.detail.value.length > 0;
    },

    // 一键登录
    async handleOneKeyLogin(e) {
      if (!this.agreedToTerms) {
        uni.showToast({
          title: "请先同意用户协议",
          icon: "none",
        });
        return;
      }

      if (e.detail.errMsg !== "getPhoneNumber:ok") {
        uni.showToast({
          title: "获取手机号失败",
          icon: "none",
        });
        return;
      }

      try {
        // 显示加载提示
        uni.showLoading({
          title: "登录中...",
        });

        // 获取微信登录code
        // const loginRes = await this.getWechatLoginCode();
        // 调用2506销售端微信登录接口
        const loginData = {
          code: e.detail.code,
          loginCode: this.loginCode
        };

        let result = await authApi.wechatLogin(loginData);
        result = {
          ...result,
          avatarUrl: this.userInfo.avatarUrl
        }
        // 使用auth管理工具保存登录信息
        authManager.saveLoginInfo(result);
        
        // 登录成功
        this.loginSuccess();
        
      } catch (error) {
        uni.showToast({
          title: error.message || "登录失败，请重试",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 获取微信登录code
    getWechatLoginCode() {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: "weixin",
          success: (res) => {
            if (res.code) {
              resolve(res.code);
            } else {
              reject(new Error('获取微信登录code失败'));
            }
          },
          fail: (err) => {
            console.error("微信登录失败:", err);
            reject(new Error('微信登录失败'));
          },
        });
      });
    },

    // 跳转到手机号登录
    goToPhoneLogin() {
      if (!this.agreedToTerms) {
        uni.showToast({
          title: "请先同意用户协议",
          icon: "none",
        });
        return;
      }
      
      // 跳转到手机号输入页面
      uni.navigateTo({
        url: `/pages/login/phone?agreedToTerms=${this.agreedToTerms}`
      });
    },

    // 登录成功
    async loginSuccess() {
      uni.showToast({
        title: "登录成功",
        icon: "success",
      });
      await cartManager.onUserLogin()
      // 跳转到主页
      setTimeout(() => {
        uni.switchTab({
          url: "/pages/index/index",
        });
      }, 1500);
    },
  },
};
</script>

<style scoped lang="scss">
.login-container {
  width: 100%;
  height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

/* 启动页样式 */
.splash-screen {
  position: relative;
  width: 100%;
  height: 100vh;
  background-image: url("https://jyoungy.oss-cn-beijing.aliyuncs.com/jyy-mini-sale/login/loginbg.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.background-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0.1;
}

.content {
  position: relative;
  z-index: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 160rpx;
}

.logo-icon {
  width: 320rpx;
  margin-bottom: 40rpx;
}

.logo-text {
  color: white;
  font-size: 48rpx;
  font-weight: bold;
}

.logo-sub {
  color: white;
  font-size: 32rpx;
  margin-top: 8rpx;
}

.brand-text {
  text-align: center;
}

.brand-title {
  color: white;
  font-size: 48rpx;
  font-weight: bold;
  display: block;
  letter-spacing: 4rpx;
  margin-bottom: 16rpx;
}

.brand-subtitle {
  color: white;
  font-size: 32rpx;
  display: block;
}

.button-section {
  width: 100%;
  margin-bottom: 80rpx;
}

.primary-btn,
.secondary-btn {
  width: 546rpx;
  height: 90rpx;
  border: none;
  border-radius: 0;
  font-size: 30rpx;
  line-height: 90rpx;
}

.primary-btn {
  background: white;
  color: #161617;
  margin-bottom: 30rpx;
}

.secondary-btn {
  background: transparent;
  color: white;
  border: 2rpx solid #cccccc;
}

.agreement-section {
  width: 546rpx;
  position: relative;
  padding-left: 48rpx;

  .agreement-checkbox-group {
    position: absolute;
    top: -12rpx;
    left: -0rpx;
  }

  .agreement-checkbox-item {
    // width: 28rpx;
    // height: 28rpx;
    // border: 2rpx solid #fafcff;
    // background-color: transparent;

    // &::after {
    //   content: "";
    //   position: absolute;
    //   top: 0px;
    //   left: 0px;
    //   width: 100%;
    //   height: 100%;
    //   background-color: red;
    //   background-size: 80%;
    //   border-radius: 8rpx;
    // }
  }
}

.agreement-checkbox {
  display: flex;
  align-items: flex-start;
}

.agreement-text {
  color: white;
  font-size: 28rpx;
  line-height: 1.4;
  margin-left: 16rpx;
}
</style>
